package com.ruibang.glass.quality.component.job;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ruibang.glass.quality.domain.req.ArchiveDefectReq;
import com.ruibang.glass.quality.domain.resp.ReinvestmentInfo;
import com.ruibang.glass.quality.entity.EverydayArchiveDefect;
import com.ruibang.glass.quality.service.EverydayArchiveDefectService;
import com.ruibang.glass.quality.service.impl.TotalEquDataServiceImpl;
import com.teaming.cloud.framework2.elastic.job3.annotation.ElasticJobScheduler;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/***
 * 归档缺陷统计
 */
@Slf4j
@ElasticJobScheduler(cron = "13 20 7 * * ?", name = "EverydayArchiveDefectTask", shardingItemParameters = "0=0", jobParameters = "parameter")
//@ElasticJobScheduler(cron = "9 * * * * ?", name = "EverydayArchiveDefectTask", shardingItemParameters = "0=0", jobParameters = "parameter")
@Component
public class EverydayArchiveDefectTask implements SimpleJob {

    @Autowired
    private TotalEquDataServiceImpl totalEquDataService;

    @Autowired
    private EverydayArchiveDefectService everydayArchiveDefectService;

    @Override
    public void execute(ShardingContext shardingContext) {
        List<ReinvestmentInfo> reinvestmentInfos = updateDayReinvestmentData();
        LocalDate now = LocalDate.now();
        String startDate = now.minusDays(7).format(DateTimeFormatter.ISO_LOCAL_DATE);
        String endDate = now.format(DateTimeFormatter.ISO_LOCAL_DATE);
        ArchiveDefectReq archiveDefectReq = new ArchiveDefectReq();
        archiveDefectReq.setStartDate(startDate);
        archiveDefectReq.setEndDate(endDate);
        List<EverydayArchiveDefect> archiveDefects = totalEquDataService.queryEverydayArchiveDefect(archiveDefectReq);
        //查询返投数
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
        if (archiveDefectReq.getStartDate() != null) {
            archiveDefectReq.setStartDate(now.minusDays(1).format(dtf));
        }
        if (archiveDefectReq.getEndDate() != null) {
            archiveDefectReq.setEndDate(now.format(dtf));
        }
        Map<String, Integer> reinvestmentMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(reinvestmentInfos)) {
            reinvestmentMap = reinvestmentInfos.stream().collect(Collectors.toMap(ReinvestmentInfo::getReinvestmentTime, ReinvestmentInfo::getReinvestmentNum, (r1, r2) -> r1));
        }

        if (CollectionUtils.isNotEmpty(archiveDefects)) {
            for (EverydayArchiveDefect archiveDefect : archiveDefects) {
                if (reinvestmentMap.get(archiveDefect.getDefectTimeKey()) != null) {
                    archiveDefect.setReinvestmentNum(reinvestmentMap.get(archiveDefect.getDefectTimeKey()));
                } else {
                    archiveDefect.setReinvestmentNum(0);
                }

                if (StringUtils.isNotBlank(archiveDefect.getDefectTimeKey())) {
                    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                    archiveDefect.setDefectTime(LocalDate.parse(archiveDefect.getDefectTimeKey(), dateTimeFormatter));
                }

                archiveDefect.setCheckMachineCode("CM1");
                if (archiveDefect.getFinishCheckNum() > 0) {
                    if (archiveDefect.getBubbleDiscardNum() > 0) {
                        archiveDefect.setBubbleDiscardRate(archiveDefect.getBubbleDiscardNum() / (float) archiveDefect.getFinishCheckNum());
                    }
                    if (archiveDefect.getOpenBubbleDiscardNum() > 0) {
                        archiveDefect.setOpenBubbleDiscardRate(archiveDefect.getOpenBubbleDiscardNum() / (float) archiveDefect.getFinishCheckNum());
                    } else {
                        archiveDefect.setOpenBubbleDiscardRate(0f);
                    }

                    if (archiveDefect.getStoneDiscardNum() > 0) {
                        archiveDefect.setStoneDiscardRate(archiveDefect.getStoneDiscardNum() / (float) archiveDefect.getFinishCheckNum());
                    }

                    if (archiveDefect.getPlatinumDiscardNum() > 0) {
                        archiveDefect.setPlatinumDiscardRate(archiveDefect.getPlatinumDiscardNum() / (float) archiveDefect.getFinishCheckNum());
                    }
                }
            }
            archiveDefectReq.setStartDate(startDate);
            archiveDefectReq.setEndDate(endDate);
            everydayArchiveDefectService.deleteByParam(archiveDefectReq);
            everydayArchiveDefectService.saveBatch(archiveDefects);
        }

    }

    /**
     * 更新一个月每天待返投数据
     *
     * @return
     */
    private List<ReinvestmentInfo> updateDayReinvestmentData() {
        LocalDateTime now = LocalDateTime.now();
        String startDate = now.minusDays(30).format(DateTimeFormatter.ISO_LOCAL_DATE);
        String endDate = now.format(DateTimeFormatter.ISO_LOCAL_DATE);
        ArchiveDefectReq archiveDefectReq = new ArchiveDefectReq();
        archiveDefectReq.setStartDate(startDate);
        archiveDefectReq.setEndDate(endDate);
        List<ReinvestmentInfo> reinvestmentInfos = everydayArchiveDefectService.getDayReinvestmentNum(archiveDefectReq);
        List<EverydayArchiveDefect> everydayArchiveDefects = everydayArchiveDefectService.queryEveryDayByTime(archiveDefectReq);
        if (CollectionUtils.isNotEmpty(everydayArchiveDefects) && CollectionUtils.isNotEmpty(reinvestmentInfos)) {
            Map<String, Integer> reinvestmentMap = reinvestmentInfos.stream().collect(Collectors.toMap(ReinvestmentInfo::getReinvestmentTime, ReinvestmentInfo::getReinvestmentNum, (r1, r2) -> r1));
            List<EverydayArchiveDefect> updateDatas = new ArrayList<>();
            for (EverydayArchiveDefect everydayArchiveDefect : everydayArchiveDefects) {
                if (reinvestmentMap.get(everydayArchiveDefect.getDefectTimeKey()) != null) {
                    if (everydayArchiveDefect.getReinvestmentNum() != reinvestmentMap.get(everydayArchiveDefect.getDefectTimeKey())) {
                        everydayArchiveDefect.setReinvestmentNum(reinvestmentMap.get(everydayArchiveDefect.getDefectTimeKey()));
                        updateDatas.add(everydayArchiveDefect);
                    }
                }

            }

            if (CollectionUtils.isNotEmpty(updateDatas)) {
                everydayArchiveDefectService.updateBatchById(updateDatas);
            }
        }
        return reinvestmentInfos;
    }


}
